<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>Hello MUI</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<link rel="stylesheet" href="css/mui.min.css">
		<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css"/>
		<style>
			html,body {
				background-color: #efeff4;
				color: black;
			}
			.mui-pull {
				padding: 0 0;
				border: none;
			}
			.mui-pull> .mui-pull-left{
				line-height: 40px;
				color: whitesmoke;
				font-size: 14px;
				font-weight: 600;
				height: 100%;
				width: 25.6%;
				padding: 0 10px;
				background-color: #FF3366;
			}
			.mui-pull> .jiezhang{
				margin:0px 0px;
				width: 48%;
				border: none;
				border-radius: 0 0;
				height: 100%;
				background-color: #FF6666;
			}
			
			.mui-table-view> .goods{
				height: 150px;
				/*background-color: rgb(239,239,244);*/
			}
			h3{
				color: #CC3366;
				font-size: 12px;
				line-height: 14px;
			}
			.goods> div{
				height: 100%;
			}
			.goods .mui-checkbox> input{
				margin: 37% 0 0 15px;
			}
			.goods div> img{
				box-shadow: -5px -5px 4px gray ;
				width: 50%;
				height: 100%;
			}
			.goods div> *{
				display: block;
			}
			.goods div> .spec{
				width: 45%;
				height: 100%;
			}
			.goods div> .spec p{
				font-size: 12px;
				line-height: 16px;
			}
			.mui-numbox{
				/*margin-top: 1%;*/
				height: 20%;
			}
			.mui-numbox> .btn{
				background-color: papayawhip;
				border-radius: 0px 0px;
			}
			.fengexian{
				width: 100%;
				padding: 0 0;
				border: 10px solid #009999;
			}
			#empty{
				font-weight: bold;
				text-shadow: 1px -1px blanchedalmond;
				color: lightgray;
				display: block;
				width: 100%;
				height: 100%;
				text-align: center;
				line-height: 100%;
				background-color: gray;
			}
			.mui-scroll-wrapper{
				padding-top: 10%;
				padding-bottom: 10%;
			}
			.top{
				opacity: 0.8;
			}
			.delete{
				margin: auto center;
				display: none;
			}
			.allselect{
				width: 30%;
				margin: auto center;
			}
		</style>
	</head>

	<body>
		<div class="mui-content">
			<div class="mui-bar top">
				<button class="mui-btn mui-btn-success mui-pull-left allselect">全选</button>
				<button class="mui-btn mui-btn-danger mui-pull-right delete">删除</button>
			</div>
			<div class="mui-scroll-wrapper">
				<div style="background-color: yellowgreen;">
					<!--购物车商品列表页-->
					<ul class="mui-table-view" id="Car">
						
					</ul>
				</div>
			</div>
			<div class="mui-bar  mui-pull">
				<div class="mui-pull-left mui-icon FontAwesome icon-credit-card">合计金额</div>
				<!--当打开购物车页面 首先判断是否有本地存储，如果有，发送ajax请求服务判断本地服务车存储数据标识以判断是否需要更新数据-->
				<span class="mui-pull-left  sumprice" style="font-size: 12px;">  ¥ 0.00 </span>
				<input type="hidden" id="hide" value="" />
				<button class="mui-btn-primary mui-pull-left jiezhang" style="margin: 0 0;">清算</button>
			</div>
		</div>
		</style>
	</body>
	<script src="js/mui.min.js"></script>
	<script src="js/config.js"></script>
	<script>
		mui.init({
			swipeBack:true //启用右滑关闭功能
		});
		/*document.getElementById("about").addEventListener('tap',function () {
			//获得主页面的webview
			var main = plus.webview.currentWebview().parent();
			//触发主页面的gohome事件
			mui.fire(main,'gohome');*/
//		});
		mui.plusReady(function(){
			//獲取登錄秘鑰
			var token = '20161011116366904671';
			
			var type = 'inner';
			
			//檢查是否擁有購物車本地存儲數據
			//添加購物車時，存儲一個購物車本地標識id 判斷此id即可
			var cartItem = plus.storage.getItem('cartid');
			var temp = [];
			if(cartItem){
				temp['cartid'] = cartItem.split(',');
				cartItem = plus.storage.getItem('cartname');
				temp['cartname'] = cartItem.split(',');
				cartItem = plus.storage.getItem('singleprice');
				temp['singleprice'] = cartItem.split(',');
				cartItem = plus.storage.getItem('count');
				temp['count'] = cartItem.split(',');
				cartItem = plus.storage.getItem('cartattr');
				temp['cartattr'] = cartItem.split(',');
				cartItem = plus.storage.getItem('imgurl');
				temp['imgurl'] = cartItem.split(',');
				cartItem = plus.storage.getItem('clink');
				temp['clink'] = cartItem.split(',');
				//var len = temp['cartid'].length;
				//需要組合數據
				var data = [];
				mui.each(temp,function(index,item){
					var i = index;
					mui.each(temp[index],function(index,item){
						data[index][i] = item;
					});
				});
				load(data);
				//動態添加組件需要手動初始化
				mui('.mui-numbox').numbox();
			}else{
				//如果沒有本地數據 則判斷是否登錄 登錄則從數據庫請求購物車信息 如果仍然無 則返回空
				var ip = ipconfig().ip;
				if(token){
					getData(type,token);
				}else{
//					document.getElementByClassName('mui-scroll-wrapper').append('<h3 class="mui-icon FontAwesome icon-flag" id="empty">購物車空空如也...</h3>');
				}
			}
		});
		
		/**
		 * ajax请求数据
		 * @param {token} 用户登录秘钥
		 */
		var getData = function (type,token) {
			var sessionId = token;
			var ip = ipconfig().ip;
			mui.ajax(ip+'ActCart.getCartData',{
				data:{session_id:sessionId},
				dataType:'json',
				timeout:10000,
				type:'get',
				headers:{'Content-Type':'application/json'},
				success:function(data){
					//console.log(data.data.data);
					load(data.data.data,type);
				},
				error:function(xhr,type,errorThrow){
					console.log(type);
				}
			})
			
			
		}
		
		
		
		
		
		
		//DOM寫入函數
		var load = function(cartData,type){
			var jpg = ipconfig().jpg;
			var html = [];
			mui.each(cartData,function(index,item){
				if(cartData instanceof Array){
					html.push('<li class="mui-table-view-cell mui-row goods"><div class="mui-col-xs-2 mui-checkbox"><input class="check" type="checkbox" name="goods1" /></div><div class="mui-col-xs-10"><img class="mui-pull-left" src="'+jpg+item["thumb"]+'"/><div class="spec mui-pull-right"><a href="#" class="mui-text-center"><h3 class="mui-ellipsis-2">'+item["title"]+'</h3></a><p>单价:<span class="price">'+item["marketprice"]+'</span></p><p>数量:<span class="count">'+item["total"]+'</span></p><p>属性:<span></span></p><p>合计:<span>'+item.marketprice * item.total+'</span></p><div class="mui-numbox" data-numbox-min="-1" data-numbox-max="100"><button class="mui-btn mui-numbox-btn-plus btn" type="button">+</button><input type="number" value="'+item["total"]+'" class="mui-numbox-input changeval"/><button class="mui-btn mui-numbox-btn-minus btn" type="button">-</button></div></div></div></li><div class="mui-table-view-cell fengexian"></div>')
				}else{
					html.push('<li class="mui-table-view-cell mui-row goods"><div class="mui-col-xs-2 mui-checkbox"><input class="check" type="checkbox" name="goods1"/></div><div class="mui-col-xs-10"><img class="mui-pull-left" src="'+jpg+item.thumb+'"/><div class="spec mui-pull-right mui-ellipsis-2"><a href="#" class="mui-text-center"><h3>'+item.title+'</h3></a><p>单价:<span class="price">'+item.marketprice+'</span></p><p>数量:<span class="count">'+item.total+'</span></p><p>属性:<span></span></p><p>合计:<span>'+item.marketprice * item.total+'</span></p><div class="mui-numbox" data-numbox-min="-1" data-numbox-max="100"><button class="mui-btn mui-numbox-btn-plus btn" type="button">+</button><input type="number" value="'+item.total+'" class="mui-numbox-input changeval"/><button class="mui-btn mui-numbox-btn-minus btn" type="button">-</button></div></div></div></li><div class="mui-table-view-cell fengexian"></div>')
				};
			});
			//寫入
			var parentNode = document.getElementById('Car');
			if(type=='inner'){
				parentNode.innerHTML = html.join('');
				document.getElementsByClassName('sumprice')[0].innerHTML = " ¥ "+sumCart().sumview;
				document.getElementById('hide').value = sumCart().sum;
			}else{
				parentNode.appendChild();
			}
			
			mui('.mui-numbox').numbox();
			//区域滚动插件
			mui('.mui-scroll-wrapper').scroll({
				deceleration:5000
			});
		}
		
		
		

		//是否删除购物车中物品
		//监听单击事件
		
		var index = 0;
		//给视口添加单击触发事件，进行编号
		document.addEventListener('tap',function(){
			li = document.getElementsByTagName('li');
			for(i = 0;i<li.length;i++){
			(function(k){
				li[i].addEventListener('change',function(){
					index = k;
				});
				})(i); 
			};
		});
		
		//监听check框事件//延时函数
		/**
		 * @return  判断有问题
		 */
		var del = document.getElementsByClassName('delete')[0];
		var check = document.getElementsByClassName('check');
		var fengexian = document.getElementsByClassName('fengexian');
		var in_array = function(arr,value){
			var len = arr.length;
			for(var i = 0;i<len;i++){
				if(arr[i]==value){
					return true;
				}
			}
			return false;
		}
		mui('.mui-table-view').on('click','.check',function(){
			var clen = check.length;
			var checkStatus = [];
			for(var i=0;i<clen;i++){
				checkStatus.push(check[i].checked);
			}
			//console.log(checkStatus);
			if(in_array(checkStatus,true)){
				del.style.display = 'block';
			}
			if(!in_array(checkStatus,true)){
				del.style.display = 'none';
			}
		});
		
		/**
		 *  监听删除
		 */
		del.addEventListener('tap',function(){
			var len = check.length;
			var checkSelect = [];
			var parentNode = document.getElementById('Car');
			
			mui.confirm('客官您确定要删除嘛','确认删除?',['确定','取消'],function(e){
				if(e.index == 1){
					return;
				}else{
					for(var i=0;i<len;i++){
						if(check[i].checked){
							parentNode.removeChild(li[i]);
							parentNode.removeChild(fengexian[i]);
							i--;
							len--;
						}
					}
					document.getElementsByClassName('sumprice')[0].innerHTML = " ¥ "+sumCart().sumview;
					document.getElementById('hide').value = sumCart().sum;
					mui('.mui-scroll-wrapper').scroll().scrollTo(0,0,500);
				}
			});
		}); 
		
		/**
		 * 全选
		 * @param {Element} allselect
		 */
		var allselect = document.getElementsByClassName('allselect')[0];
		var is_allselect = 0;
		allselect.addEventListener('tap',function(){
			if(is_allselect===0){
				for(var i=0;i<check.length;i++){
					check[i].checked = true;
				}
				allselect.innerText = '取消全选';
				del.style.display = 'block';
				is_allselect = 1;
			}else{
				for(var j=0;j<check.length;j++){
					check[j].checked = false;
				}
				allselect.innerText = '全选';
				del.style.display = 'none';
				is_allselect = 0;
			}
			
		});
		
		
		
		
		
		mui('.mui-table-view').on('tap','.btn',function(e){
			//根据当前触发元素追溯其父元素 兄弟元素
			var val = this.parentNode.childNodes[1].value;
			var valnode = this.parentNode.childNodes[1];
			var parentNode = this.parentNode.parentNode.parentNode.parentNode;
			var brother = parentNode.nextSibling;
			
			
			//console.log(brother);
//			alert(index);
			//抓购物车列表父级元素
			var parentCar = document.getElementById('Car');
//			parentCar.remo
//			alert(val);
			
			
			/**
			 * 单件商品合计价格
			 * @param {int}  singlesum  单件商品合计价格
			 * @param {int}  price 		单件商品价格
			 */
			var price = this.parentNode.parentNode.childNodes[1].childNodes[1].innerText;
			var singleSum = price * val;
			var singleSumDom = this.parentNode.parentNode.childNodes[4].childNodes[1];
//			alert(singleSumDom);
			singleSumDom.innerText = singleSum;
			//console.log(this.parentNode.parentNode.childNodes[1].childNodes[1].innerText);
			
			//操作购物车商品 数量属性 
			var countNode = parentNode.getElementsByClassName('count')[0];
			if(val<1){
				btnArray = ['不要了','要'];
				mui.confirm('大爷你真不要这宝贝了嘛','鸭子飞了',btnArray,function(e){
					if(e.index==1){
						valnode.value = 1; 
						countNode.innerHTML = valnode.value;
						document.getElementsByClassName('sumprice')[0].innerHTML = " ¥ "+sumCart().sumview;
						document.getElementById('hide').value = sumCart().sum;
						return;
					}else{ 
						parentCar.removeChild(parentNode);
						parentCar.removeChild(brother); 
						return;
					}
				},'div')
			}
			
			
			
			countNode.innerHTML = valnode.value;
			
			//调用金额计算器 计算金额变化并写入节点sumprice
			var sumReckon = sumCart();
			//alert(sumReckon.sumview);
			document.getElementsByClassName('sumprice')[0].innerHTML = " ¥ "+sumReckon.sumview;
			document.getElementById('hide').value = sumReckon.sum;
		});
		
		//合计金额计算器
		var sumCart = function(){
			//获取购物车 商品总数
			var account = mui('.goods');
			var len = account.length;
			//创建临时数组
			var sumTemp = [];
			for(j = 0;j<len;j++){
				//将单件商品合计价格压入 数组sumtemp
				var singlePrice = document.getElementsByClassName('price')[j].innerHTML;
				var account = document.getElementsByClassName('count')[j].innerHTML;
				var sumprice = singlePrice * account;
				sumTemp.push(sumprice);
			}
			function pow(x,y){
				return x+y;
			}
			if(sumTemp.length !==0){
				var sum = sumTemp.reduce(pow);
			}else{
				var sum = 0;
			}
			//格式化价格
			function formatNum(num,n)
			{//参数说明：num 要格式化的数字 n 保留小数位
			    num = String(num.toFixed(n));
			    var re = /(-?\d+)(\d{3})/;
			    while(re.test(num)) num = num.replace(re,"$1,$2")
			    return num;
			}
			var sumview = formatNum(sum,2);
			var obj = {
				"sum":sum,
				"sumview":sumview
			}
			return obj;
		}
		
		
	</script>
</html>